package com.sskj.fca.ui.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.widget.RxAdapterView;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.fca.R;
import com.sskj.fca.bean.ToRechargeBean;
import com.sskj.fca.bean.TxDataBean;
import com.sskj.fca.bean.WithDrawLimitBean;
import com.sskj.fca.component.DaggerUserDataComponent;
import com.sskj.fca.presenter.WithdrawActivityPresenter;
import com.sskj.fca.ui.ArrowAdapter;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

@Route(path = RConfig.APP_WITHDRAW)//提币
public class WithdrawActivity extends BaseActivity<WithdrawActivityPresenter> {
    @BindView(R.id.tv_can_use_with_draw_money)
    TextView tvCanUseWithDrawMoney;
    @BindView(R.id.et_with_draw_money)
    EditText etWithDrawMoney;
    @BindView(R.id.tvAll)
    TextView tvAll;
    @BindView(R.id.viewAllLine)
    View viewAllLine;
    @BindView(R.id.tv_can_with_draw_money)
    TextView tvCanWithDrawMoney;
    @BindView(R.id.tv_can_with_draw_usdt)
    TextView tv_can_with_draw_usdt;
    @BindView(R.id.tv_with_draw_type)
    TextView tv_with_draw_type;
    @BindView(R.id.et_with_draw_pay_pwd)
    EditText etWithDrawPayPwd;
    @BindView(R.id.et_verification_code)
    EditText etVerificationCode;
    @BindView(R.id.tvGetCode)
    TextView tvGetCode;
    @BindView(R.id.ll_usdt_address)
    LinearLayout ll_usdt_address;
    @BindView(R.id.et_withdraw_address)
    EditText et_withdraw_address;
    @BindView(R.id.tv_with_draw_type_tip)
    TextView tv_with_draw_type_tip;
    @BindView(R.id.tv_withdraw_usdt)
    TextView tv_withdraw_usdt;
    @BindView(R.id.btn_with_draw)
    Button btnWithDraw;
    @BindView(R.id.spinner_way)
    Spinner spinner_way;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.ll_input_money)
    LinearLayout ll_input_money;
    @Inject
    UserViewModel userViewModel;
    @Autowired
    String moneyType;
    private UserData userData;
    private DisposableSubscriber disposableSubscriber;

    private float canMin;//最低提现USDT
    private float canMinCNY;//最低提现CNY
    private float myUSDT;//我的USDT
    private float myCNY;//我的CNY
    private String rate;//汇率
    private float beiShu;//提现倍数


    private int withDrawType;//提币类型
    private String withWayType;//提币通道

    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_withdraw;
    }

    @Override
    public WithdrawActivityPresenter getPresenter() {
        return new WithdrawActivityPresenter();
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        setTitle(App.INSTANCE.getString(R.string.app_activity_recharge));
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });

        mPresenter.getUSDTInfo();
        mPresenter.getWithDrawLimit();

        List<String> payWays = Arrays.asList(getResources().getStringArray(R.array.app_with_draw_ways));
        ArrowAdapter spinnerWayAdapter = new ArrowAdapter(this,
                R.layout.app_item_user_type, payWays);
        spinnerWayAdapter.setDropDownViewResource(R.layout.app_item_withdraw_type_drop);
        spinner_way.setAdapter(spinnerWayAdapter);
        spinner_way.setSelection(0);
        spinner_way.setDropDownVerticalOffset(10);
        RxAdapterView.itemSelections(spinner_way)
                .subscribe(pos -> {
                    etWithDrawMoney.setText("");
                    withWayType = pos + 1 + "";
                    spinner.setSelection(1);
                    switch (pos) {
                        case 0:
                            spinner.setVisibility(View.VISIBLE);
                            tv_withdraw_usdt.setVisibility(View.GONE);
//                            ll_input_money.setVisibility(View.VISIBLE);
//                            tv_can_with_draw_usdt.setVisibility(View.GONE);
//                            tvCanWithDrawMoney.setVisibility(View.VISIBLE);
//                            if (withDrawType == 0) {
//                                ll_usdt_address.setVisibility(View.VISIBLE);
//                            }
//                            etWithDrawMoney.setText("");
//                            if (withDrawType == 1) {
//                                tv_with_draw_type_tip.setText("提现金额");
//                                if (!TextUtils.isEmpty(String.valueOf(canMin)) &&
//                                        !TextUtils.isEmpty(rate)) {
//                                    BigDecimal usdt = new BigDecimal(canMin);
//                                    BigDecimal tate = new BigDecimal(rate);
//                                    etWithDrawMoney.setHint("最小提现金额 " + NumberUtil.keep4(String.valueOf(usdt.multiply(tate))) + " CNY");
//                                } else {
//                                    etWithDrawMoney.setHint("");
//                                }
//                            }
                            break;
                        case 1:
                            withDrawType = 1;
                            spinner.setVisibility(View.GONE);
                            tv_withdraw_usdt.setVisibility(View.VISIBLE);
                            ll_usdt_address.setVisibility(View.GONE);
                            tv_with_draw_type_tip.setText("提现金额");
                            if (!TextUtils.isEmpty(String.valueOf(canMin)) &&
                                    !TextUtils.isEmpty(rate)) {
                                BigDecimal usdt = new BigDecimal(canMin);
                                BigDecimal tate = new BigDecimal(rate);
                                etWithDrawMoney.setHint("最小提现金额 " + NumberUtil.keep4(String.valueOf(usdt.multiply(tate))) + " CNY");
                            } else {
                                etWithDrawMoney.setHint("");
                            }
//                            ll_input_money.setVisibility(View.GONE);
//                            tv_can_with_draw_usdt.setVisibility(View.VISIBLE);
//                            tvCanWithDrawMoney.setVisibility(View.GONE);
//                            ll_usdt_address.setVisibility(View.GONE);
//                            tv_with_draw_type_tip.setText("提币数量");
//                            etWithDrawMoney.setText("");
//                            if (!TextUtils.isEmpty(String.valueOf(canMin))) {
//                                etWithDrawMoney.setHint("最小提币数量 " + canMin + " USDT");
//                            } else {
//                                etWithDrawMoney.setHint("");
//                            }
                            break;
                    }
                });


        List<String> payTypes = Arrays.asList(getResources().getStringArray(R.array.app_with_draw_types));
        ArrowAdapter spinnerTypeAdapter = new ArrowAdapter(this,
                R.layout.app_item_user_type, payTypes);
        spinnerTypeAdapter.setDropDownViewResource(R.layout.app_item_withdraw_type_drop);
        spinner.setAdapter(spinnerTypeAdapter);
        spinner.setSelection(1);
        spinner.setDropDownVerticalOffset(10);
        RxAdapterView.itemSelections(spinner)
                .subscribe(pos -> {
                    etWithDrawMoney.setText("");
                    withDrawType = pos;
                    switch (pos) {
                        case 0:
                            ll_usdt_address.setVisibility(View.VISIBLE);
                            tv_with_draw_type_tip.setText("提币数量");
                            if (!TextUtils.isEmpty(String.valueOf(canMin))) {
                                etWithDrawMoney.setHint("最小提币数量 " + canMin + " USDT");
                            } else {
                                etWithDrawMoney.setHint("");
                            }
                            break;
                        case 1:
                            ll_usdt_address.setVisibility(View.GONE);
                            tv_with_draw_type_tip.setText("提现金额");
                            if (!TextUtils.isEmpty(String.valueOf(canMin)) &&
                                    !TextUtils.isEmpty(rate)) {
                                BigDecimal usdt = new BigDecimal(canMin);
                                BigDecimal tate = new BigDecimal(rate);
                                etWithDrawMoney.setHint("最小提现金额 " + NumberUtil.keep4(String.valueOf(usdt.multiply(tate))) + " CNY");
                            } else {
                                etWithDrawMoney.setHint("");
                            }
                            break;
                    }
                });

        ClickUtil.click(tvGetCode, () -> {
            mPresenter.sendCode(userData == null ? "" : userData.getTel());
        });
        ClickUtil.click(tvAll, () -> {
//            if (withWayType == 1) {
//                if (!TextUtils.isEmpty(String.valueOf(myUSDT))) {
//                    etWithDrawMoney.setText(String.valueOf(myUSDT));
//                }
//                return;
//            }
            switch (withDrawType) {
                case 0:
                    if (!TextUtils.isEmpty(String.valueOf(myUSDT))) {
                        etWithDrawMoney.setText(String.valueOf(myUSDT));
                    }
                    break;
                case 1:
                    if (!TextUtils.isEmpty(String.valueOf(myUSDT)) &&
                            !TextUtils.isEmpty(rate)) {
                        BigDecimal usdt = new BigDecimal(myUSDT);
                        BigDecimal tate = new BigDecimal(rate);
                        etWithDrawMoney.setText(NumberUtil.keep4(String.valueOf(usdt.multiply(tate))));
                    } else {
                        etWithDrawMoney.setText("");
                    }
                    break;
            }
        });
        ClickUtil.click(btnWithDraw, () -> {
            if (TextUtils.isEmpty(String.valueOf(myUSDT))) {
                ToastUtil.showShort("获取信息失败");
                return;
            }
            if (TextUtils.isEmpty(etWithDrawPayPwd.getText().toString())) {
                ToastUtil.showShort("请输入支付密码");
                return;
            }
//            if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) % beiShu != 0) {
//                ToastUtil.showShort("提币数量需为" + beiShu + "的倍数");
//                return;
//            }
            if (TextUtils.isEmpty(etVerificationCode.getText().toString())) {
                ToastUtil.showShort("请输入验证码");
                return;
            }
            if (TextUtils.isEmpty(etWithDrawMoney.getText().toString())) {
                ToastUtil.showShort("请输入提币数量");
                return;
            }
            /**
             * 移除通道二
             */
            if (withDrawType == 0) {//USDT
                if (TextUtils.isEmpty(et_withdraw_address.getText().toString().trim())) {
                    ToastUtil.showShort("请输入钱包地址");
                    return;
                }
//                if (et_withdraw_address.getText().equals("请输入钱包地址")) {
//                }
                if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) < canMin) {
                    ToastUtil.showShort("提币数量不能小于" + canMin);
                    return;
                }
                if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) > myUSDT) {
                    ToastUtil.showShort("余额不足");
                    return;
                }
                mPresenter.withDraw(withWayType, etVerificationCode.getText().toString()
                        , et_withdraw_address.getText().toString().trim()
                        , etWithDrawMoney.getText().toString().trim()
                        , etWithDrawPayPwd.getText().toString()
                        , "2");
            } else if (withDrawType == 1) {//CNY
                if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) < canMinCNY) {
                    ToastUtil.showShort("提现金额不能小于" + canMinCNY);
                    return;
                }
                if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) > myCNY) {
                    ToastUtil.showShort("余额不足");
                    return;
                }
                BigDecimal withDrawCNY = new BigDecimal(etWithDrawMoney.getText().toString().trim());
                BigDecimal bigRate = new BigDecimal(rate);
                mPresenter.withDraw(withWayType, etVerificationCode.getText().toString()
                        , etWithDrawMoney.getText().toString().trim()
                        , txfloat(Double.valueOf(etWithDrawMoney.getText().toString().trim()), Double.valueOf(rate))
//                        , NumberUtil.keep4(String.valueOf(withDrawCNY.divide(bigRate, BigDecimal.ROUND_CEILING)))
//                        , NumberUtil.keep4(String.valueOf(div(withDrawCNY, bigRate, 4)))
                        , etWithDrawPayPwd.getText().toString()
                        , "1");

            }
            /*if (withWayType == 0) {
                if (TextUtils.isEmpty(etWithDrawMoney.getText().toString())) {
                    ToastUtil.showShort("请输入提币数量");
                    return;
                }
                if (withDrawType == 0) {//USDT
                    if (tv_withdraw_address.getText().equals("请先设置钱包地址")) {
                        ToastUtil.showShort("请先设置钱包地址");
                        return;
                    }
                    if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) < canMin) {
                        ToastUtil.showShort("提币数量不能小于" + canMin);
                        return;
                    }
                    if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) > myUSDT) {
                        ToastUtil.showShort("余额不足");
                        return;
                    }
                    mPresenter.withDraw(etVerificationCode.getText().toString()
                            , tv_withdraw_address.getText().toString().trim()
                            , etWithDrawMoney.getText().toString().trim()
                            , etWithDrawPayPwd.getText().toString()
                            , "2");
                } else if (withDrawType == 1) {//CNY
                    if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) < canMinCNY) {
                        ToastUtil.showShort("提现金额不能小于" + canMinCNY);
                        return;
                    }
                    if (Float.valueOf(etWithDrawMoney.getText().toString().trim()) > myCNY) {
                        ToastUtil.showShort("余额不足");
                        return;
                    }
                    BigDecimal withDrawCNY = new BigDecimal(etWithDrawMoney.getText().toString().trim());
                    BigDecimal bigRate = new BigDecimal(rate);
                    mPresenter.withDraw(etVerificationCode.getText().toString()
                            , tv_withdraw_address.getText().toString().trim()
                            , NumberUtil.keep4(String.valueOf(withDrawCNY.divide(bigRate, BigDecimal.ROUND_CEILING)))
                            , etWithDrawPayPwd.getText().toString()
                            , "1");

                }
            } else if (withWayType == 1) {
                mPresenter.withDrawTwo(etVerificationCode.getText().toString()
                        , etWithDrawPayPwd.getText().toString());
            }*/
        });
    }

    public void sendCodeOk() {
        ToastUtil.showShort("验证码发送成功");
        startCount();
    }

    public void sendCodeError() {
        ToastUtil.showShort("验证码发送失败");
    }

    public void startCount() {
        tvGetCode.setEnabled(false);
        DisposUtil.close(disposableSubscriber);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                tvGetCode.setText(String.format(App.INSTANCE.getString(R.string.app_count_down_register), time));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                tvGetCode.setText("再次获取验证码");
                tvGetCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }
            }
        };
        etVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 6) {
                    btnWithDraw.setEnabled(true);
                } else {
                    btnWithDraw.setEnabled(false);
                }
            }
        });

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        DisposUtil.close(disposableSubscriber);
        super.onDestroy();
    }

    public void updateQC(UserBean userBean) {
        myUSDT = Float.valueOf(userBean.getBalance_cny());
        mPresenter.getTxData();
    }

    public void getTxDataSuccess(TxDataBean txDataBean) {
        if (!TextUtils.isEmpty(txDataBean.getUsdt_addr())) {
            etWithDrawMoney.setText(txDataBean.getUsdt_addr());
        }
        rate = txDataBean.getUsdt_rate();
        mPresenter.getWithDrawLimit();
    }

    public void updataWithDrawLimit(WithDrawLimitBean withDrawLimitBean) {
        canMin = withDrawLimitBean.getQianshu2_usdt();
        beiShu = withDrawLimitBean.getBeishu2_usdt();
        if (!TextUtils.isEmpty(String.valueOf(canMin))) {
            etWithDrawMoney.setHint("最小提币数量 " + canMin + " USDT");
        } else {
            etWithDrawMoney.setHint("");
        }
        if (!TextUtils.isEmpty(String.valueOf(myUSDT)) && !TextUtils.isEmpty(rate)) {
            BigDecimal bigMin = new BigDecimal(canMin);
            BigDecimal bigUsdt = new BigDecimal(myUSDT);
            BigDecimal bigRate = new BigDecimal(rate);
            etWithDrawMoney.setHint("最小提现金额 " + NumberUtil.keep4(String.valueOf(bigMin.multiply(bigRate))) + " CNY");
            canMinCNY = Float.valueOf(NumberUtil.keep4(String.valueOf(bigMin.multiply(bigRate))));
            myCNY = Float.valueOf(NumberUtil.keep4(String.valueOf(bigUsdt.multiply(bigRate))));
            tvCanUseWithDrawMoney.setText(myUSDT + "USDT ≈ " + NumberUtil.keep4(String.valueOf(bigUsdt.multiply(bigRate))) + "CNY");
            tv_can_with_draw_usdt.setText("可提币数量 " + myUSDT + " USDT");
            tvCanWithDrawMoney.setText("可提币数量 " + myUSDT + "USDT ≈ " + NumberUtil.keep4(String.valueOf(bigUsdt.multiply(bigRate))) + "CNY");
        }
    }

    public void withDrawSuccess() {
        finish();
    }

    public void withDrawSuccessTwo(ToRechargeBean toRechargeBean) {
        ARouter.getInstance().build(RConfig.APP_RECHATRGE_WEBVIEW)
                .withString(Constans.RECHARGE_URL, toRechargeBean.getUrl())
                .withString(Constans.WEBVIEW_TYPE, "提币")
                .navigation();

    }

    public static String txfloat(double a, double b) {
        DecimalFormat df = new DecimalFormat("0.0000");//设置保留位数
        return df.format(a / b);
    }

}
